package com.example.jdktest.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @WebFilter 需要配合@ServletComponentScan使用。不然无效. filter的本质是servlet。
 */
//@Component
@WebFilter(urlPatterns = {"/getUser"})
public class MyFilter implements Filter {

    @Value("#{'${user.username:dangwu}'.split(',')}")
    private List<String> username;
    @Value("${user.age}")
    private String age;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        System.out.println("TestFilter,"+request.getRequestURI());
        String name = request.getHeader("name");
        System.out.println(JSON.toJSONString(username));
        if ("dangwen".equals(name)){
            System.out.println(JSON.toJSONString(username) +":"+age);
        } else {
            response.sendRedirect("/doFilter");
//            servletRequest.getRequestDispatcher("/doFilter").forward(servletRequest,servletResponse);//报错，返回类型问题
        }

        //执行
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
